/*
 * @lc app=leetcode id=151 lang=cpp
 *
 * [151] Reverse Words in a String
 */
class Solution {
public:
    string reverseWords(string s) {

        string ret;
        int len = s.size();
        vector<string> slices;

        int idx = 0;
        int stIdx = 0;
        while (idx < len) {
            while (idx < len && s[idx] == ' ') 
                idx++;

            if (idx >= len) {
                break;
            }

            stIdx = idx;

            while (idx < len && s[idx] != ' ') 
                idx++;

            if (idx - stIdx > 0) {
                slices.push_back(s.substr(stIdx, idx-stIdx));
            }
        }

        return appendSlice(slices);
    }

    string appendSlice(const vector<string>& slices) {

        string ret;

        int len = slices.size();
        int i = len-1;
        for (; i>=0; i--) {
            if (i < len-1) {
                ret += ' ';
            }
            ret += slices[i];
        }

        return ret;
    }
};

